import * as fs from 'fs'
import * as path from 'path'
import { ServiceAll } from '../../interface'
import { UserServiceImpl } from './user'
import { UserRoleServiceImpl } from './role'
import { UserPermissionServiceImpl } from './permission'
import { logger } from 'f2e-server3'

export interface ServiceCreatorProps {
    /** 所有数据存储目录
     * @default '.f2e_cache/db_auth'
    */
    db_path?: string;
    /** 支持免登录的用户名,需要跟持久化数据的用户名一致 */
    mock_user?: string;
}
export const createService = (props: ServiceCreatorProps): ServiceAll  => {
    const { db_path = '.f2e_cache/db_auth', mock_user } = props
    const path_real = path.resolve(process.cwd(), db_path)
    if (!fs.existsSync(path_real)) {
        fs.mkdirSync(path_real, { recursive: true })
    }
    const db_path_user = path.join(path_real, 'user.json')
    const db_path_role = path.join(path_real, 'role.json')
    const db_path_permission = path.join(path_real, 'permission.json')
    const userService = new UserServiceImpl(db_path_user, mock_user)
    const userRoleService = new UserRoleServiceImpl(db_path_role)
    const userPermissionService = new UserPermissionServiceImpl(db_path_permission)
    return {
        userService,
        userRoleService,
        userPermissionService,
        init: async function (data) {
            const perms = await userPermissionService.permissionList({})
            if (!perms.data?.total) {
                logger.info('初始化权限数据')
                await userService.userCreate(data.users)
                await userRoleService.roleCreate(data.roles)
                await userPermissionService.permissionCreate(data.permissions)
                logger.info('初始化权限数据完成')
            }
        },
    }
}
export default createService;
